//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Activities;

namespace TridentBasicActivities.Activities
{
    /// <summary>
    /// This class is used to validate the For activity.
    /// This will be used to check if the values mentioned will result in an infinite loop.
    /// </summary>
    public class ValidateForActivity : CompositeActivityValidator
    {
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            if (null == manager)
            {
                throw new ArgumentNullException("manager");
            }

            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }

            ForActivity activityToValidate = obj as ForActivity;

            if (null == activityToValidate)
            {
                throw new ArgumentException("This validator can only be used by the ForActivity.", "obj");
            }

            ValidationErrorCollection errors = base.Validate(manager, obj);

            if (!ValidateParameters(activityToValidate))
            {
                ValidationError error = 
                    new ValidationError("The property values provided for the For loop are invalid", 100, false);
                error.UserData.Add("INFINITE_LOOP", "The values result in an infinite loop");
                errors.Add(error);
            }
            
            return errors;
        }

        /// <summary>
        /// Initial validation of parameters.
        /// </summary>
        /// <returns>True if parameters have valid values.</returns>
        private static bool ValidateParameters(ForActivity activity)
        {
            if (activity.Step > 0)
            {
                if (activity.Start <= activity.End)
                {
                    return true;
                }
            }
            else if (activity.Step < 0)
            {
                if (activity.Start >= activity.End)
                {
                    return true;
                }
            }
            return false;
        }
    }
}

